var express = require('express');
var router = express.Router();
var crypto=require('crypto');
var fs=require('fs');
var	User=require('../models/user.js');
var Post=require('../models/post.js');
var Comment=require('../models/comment.js');
/*主页*/
router.get('/', function(req, res) {
	var page=req.query.p?parseInt(req.query.p):1;

	Post.getTen(null,page,function(err,posts,total){
		console.log(total);
		if(err){
			posts=[];
		}
		if(((page-1)*10+posts.length)>total){
			req.flash('error','参数错误！');
			return res.redirect('back');
		}
		res.render('index', {
			title: '主页',
			page:page,
			isFirstPage:(page-1)==0,
			isLastPage:((page-1)*10+posts.length)==total,
			user:req.session.user,
			posts:posts,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
	});	
});

/*登录*/
router.get('/login', function(req, res) {
	checkNotLogin(req,res);
	res.render('login', {
		title: '登录',
		user:req.session.user,
		success:req.flash('success').toString(),
		error:req.flash('error').toString()
	});
});
router.post('/login', function(req, res) {
	var name=req.body.name;
	var password=req.body.password;
	var md5=crypto.createHash('md5');
	var passwordMd5=md5.update(password).digest('hex');
	//检查用户否存在
	User.get(name,function(err,user){
		if(!user){
			req.flash('error','用户不存在！');
			return res.redirect('/login');
		}
		//检查密码是否一致
		if(user.password!=passwordMd5){
			req.flash('error','密码错误！');
			return res.redirect('/login');
		}
		//用户名和密码都一致后，将用户信息存入session
		req.session.user=user;
		req.flash('success','登陆成功！');
		res.redirect('/');
	});
});

/*注册*/
router.get('/reg', function(req, res, next) {
	checkNotLogin(req,res);
	res.render('reg', {
		title: '注册',
		user:req.session.user,
		success:req.flash('success').toString(),
		error:req.flash('error').toString()
	});
});
router.post('/reg', function(req, res) {
	var name=req.body.name,
		password=req.body.password,
		password_repeat=req.body.password_repeat,
		email=req.body.email;

	//检验两次密码是否一致
	if(password_repeat!=password){
		console.log('两次输入的密码不一致！');
		req.flash('error','两次输入的密码不一致！');
		return res.redirect('/reg');//返回注册页面
	}

	//生成密码的MD5值
	var md5=crypto.createHash('md5');
	password=md5.update(req.body.password).digest('hex');
	var newUser=new User({
		name:req.body.name,
		password:password,
		email:req.body.email
	});
	console.log(newUser);

	//检查用户名是否存在
	User.get(newUser.name,function(err,user){
		if(err){
            req.flash('error',err);
            return res.redirect('/');
        }
		if(user){
			console.log('用户已存在！');
			req.flash('error','用户已存在！');
			return res.redirect('/reg');
		}

		//如果用户不存在则添加新用户
		newUser.save(function(err,user){
			
			if(err){
				req.flash('error',err);
				return res.redirect('/reg');
			}
			
			console.log('注册成功！');
			req.flash('success','注册成功！');
			req.session.user=user;
			res.redirect('/');
		});
	});
});

/*发表*/
router.get('/post', function(req, res) {
	checkLogin(req,res);
	res.render('post', {
		title: '发表',
		user:req.session.user,
		success:req.flash('success').toString(),
		error:req.flash('error').toString()
	});
});
router.post('/post', function(req, res) {
	checkLogin(req,res);
	var currentUser=req.session.user;
	var title=req.body.title;
	var post=req.body.post;
	var tags=[req.body.tag1,req.body.tag2,req.body.tag3];
	var postObject=new Post(currentUser.name,title,tags,post);
	console.log(postObject);
	postObject.save(function(err){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		req.flash('success','发布成功！');
		res.redirect('/');
	});
});

/*登出*/
router.get('/logout', function(req, res) {
	checkLogin(req,res);
	req.session.user=null;
	req.flash('success','登出成功！');
	res.redirect('/');
});

/*上传*/
router.get('/upload',function(req,res){
	checkLogin(req,res);
	res.render('upload',{
		title:'文件上传',
		user:req.session.user,
		success:req.flash('success').toString(),
		error:req.flash('error').toString()
	});
});
router.post('/upload',function(req,res){
	// var files=req.body.file;
	// console.log(typeof(files));
	// for(var i in files){
	// 	if(files[i].size==0){
	// 		fs.unlinkSync(files[i].path);
	// 		console.log('Successfully removed an empty file!');
	// 	}
	// 	else{
	// 		var target_path='./public/images/'+files[i].name;
	// 		fs.renameSync(files[i].path, target_path);
	// 		console.log('Successfully renamed a file!');
	// 	}
	// }
	// req.flash('success','文件上传成功！');
	// res.redirect('/upload');
});

/*根据作者获得文章*/
router.get('/u/:name',function(req,res){
	var page=req.query.p?parseInt(req.query.p):1;
	User.get(req.params.name,function(err,user){
		if(!user){
			req.flash('用户不存在！');
			return res.redirect('/');
		}
		Post.getTen(user.name,page,function(err,posts,total){
			if(err){
				req.flash('error',err);
				return res.redirect('/');
			}
			if(((page-1)*10+posts.length)>total){
				req.flash('error','参数错误！');
				return res.redirect('back');
			}
			res.render('user',{
				title:user.name,
				posts:posts,
				page:page,
				isFirstPage:(page-1)==0,
				isLastPage:((page-1)*10+posts.length)==total,
				user:req.session.user,
				success:req.flash('success').toString(),
				error:req.flash('error').toString()
			});
		});
	});
});

/*根据作者日期标题获得文章具体信息*/
router.get('/u/:name/:day/:title',function(req,res){
	var name=req.params.name;
	var day=req.params.day;
	var title=req.params.title;
	Post.getOne(name,day,title,function(err,post){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		res.render('article',{
			title:title,
			post:post,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
	});
});
router.post('/u/:name/:day/:title',function(req,res){
	var date=new Date();
	var time=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+(date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes());
	var comment={
		name:req.body.name,
		email:req.body.email,
		website:req.body.website,
		time:time,
		content:req.body.content
	};
	var newComment=new Comment(
		req.params.name,
		req.params.day,
		req.params.title,
		comment
	);
	newComment.save(function(err){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		req.flash('success','留言成功！');
		res.redirect('back');
	});
});

/*编辑文章*/
router.get('/edit/:name/:day/:title',function(req,res){
	checkLogin(req,res);
	var name=req.params.name;
	var day=req.params.day;
	var title=req.params.title;
	Post.edit(name,day,title,function(err,post){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		res.render('edit',{
			title:'编辑',
			post:post,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
	});
});
router.post('/edit/:name/:day/:title',function(req,res){
	checkLogin(req,res);
	var name=req.params.name;
	var day=req.params.day;
	var title=req.params.title;
	var post=req.body.post;
	Post.update(name,day,title,post,function(err){
		var url='/u/'+name+'/'+day+'/'+title;
		if(err){
			req.flash('error',err);
			res.redirect(url);
		}
		req.flash('success','修改成功！');
		res.redirect(url);
	});
});

/*删除文章*/
router.get('/remove/:name/:day/:title',function(req,res){
	checkLogin(req,res);
	var name=req.params.name;
	var day=req.params.day;
	var title=req.params.title;
	Post.remove(name,day,title,function(err){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		req.flash('success','删除成功！');
		res.redirect('/');
	});
});

/*查看存档*/
router.get('/archive',function(req,res){
	Post.getArchive(function(err,posts){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		
		res.render('archive',{
			title:'存档',
			posts:posts,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
	});
});

/*查看标签*/
router.get('/tags',function(req,res){
	console.log("get tags page!");
	Post.getTags(function(err,posts){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		res.render('tags',{
			title:'标签',
			posts:posts,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
	});
});

module.exports = router;

/*检验用户是否已经登录*/
function checkLogin(req,res){
	if(!req.session.user){
		req.flash('error','用户未登录！');
		res.redirect('/login');
	}
}
/*检验用户是否没有登录*/
function checkNotLogin(req,res){
	if(req.session.user){
		req.flash('error','用户已登录！');
		res.redirect('back');
	}
}